package com.summer.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.summer.common.R;
import com.summer.entity.Category;
import com.summer.entity.SetMeal;
import com.summer.entity.SetmealDto;
import com.summer.service.CategoryService;
import com.summer.service.SetMealService;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {

    @Autowired
    private SetMealService setMealService;

    @Autowired
    private CacheManager cacheManager;

    @Autowired
    private CategoryService categoryService;

    /**
     * 添加套餐(双表操作)
     * @param setmealDto DTO
     * @return 返回字符串信息
     */
    @PostMapping
    //优化：删除此套餐分类的redis缓存
    @CacheEvict(value = "setmealCache", key = "'category_' + #setmealDto.categoryId")
    public R<String> addSetMeal(@RequestBody SetmealDto setmealDto){
        log.info("添加套餐请求，DTO={}",setmealDto.toString());
        //1. 多表操作，service层创建方法
        setMealService.addSetMealAndSetMealDish(setmealDto);
        //2. 返回字符串信息
        return R.success("添加成功");
    }

    /**
     * 套餐分页条件查询请求
     * @param page 当前页
     * @param pageSize 每页显示数目
     * @param name 迷糊查询条件
     * @return 返回分页数据
     */
    @GetMapping("/page")
    public R<Page<SetmealDto>> getByPageAndCondition(int page, int pageSize, String name){
        log.info("套餐分页条件查询请求，page=" +page+ "，pageSize="+pageSize+"，name="+name);
        // 1. setmeal的分页构造器
        Page<SetMeal> setMealPage = new Page<>(page, pageSize);
        // 2. 条件构造器
        LambdaQueryWrapper<SetMeal> lqw = new LambdaQueryWrapper<>();
        lqw.like(SetMeal::getName, name);
        lqw.orderByAsc(SetMeal::getCategoryId).orderByAsc(SetMeal::getPrice);
        // 3. 调用分页api分页查询
        setMealService.page(setMealPage);
        // 4. 封装dto分页构造器
        Page<SetmealDto> setmealDtoPage = new Page<>();

        // 4.1 将setMealPage除了records的其他属性copy
        BeanUtils.copyProperties(setMealPage, setmealDtoPage);

        // 4.2 设置setmealDtoPage的records属性
        List<SetmealDto> setmealDtoList = new ArrayList<>();
        for (SetMeal setMeal : setMealPage.getRecords()) {
            // 封装setmealDto
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(setMeal, setmealDto);
            // 根据categoryId查询categoryName
            Category category = categoryService.getById(setMeal.getCategoryId());
            setmealDto.setCategoryName(category.getName());
            setmealDtoList.add(setmealDto);
        }
        setmealDtoPage.setRecords(setmealDtoList);
        // 5. 返回dto分页数据
        return R.success(setmealDtoPage);
    }

    /**
     *  批量删除套餐
     * @param ids ids数组
     * @return 返回字符串
     */
    @DeleteMapping
    //优化：删除全部套餐分类的redis缓存
    @CacheEvict(value = "setmealCache", allEntries = true)
    public R<String> deleteByIds(@RequestParam List<Long> ids){
        log.info("批量删除套餐请求，ids={}",ids.toString());
        // 删除多表，业务层创建方法
        setMealService.deleteByIds(ids);
        return R.success("删除成功");
    }

    /**
     * 批量修改套餐状态
     * @param status 接收状态， 0停售， 1在售
     * @param ids id数组
     * @return 返回字符串
     */
    @PostMapping("/status/{status}")
    //优化：删除全部套餐分类的redis缓存
    @CacheEvict(value = "setmealCache", allEntries = true)
    public R<String> updateSetmealStatusByIds(@PathVariable int status, long[] ids){
        log.info("批量修改套餐状态请求，请求ids=" + Arrays.toString(ids) + "Status=" + status);
        //1. 调用service修改
        List<SetMeal> setMealList = new ArrayList<>();
        for (long id : ids) {
            SetMeal setMeal = new SetMeal();
            setMeal.setId(id);
            setMeal.setStatus(status);
            setMealList.add(setMeal);
        }
        setMealService.updateBatchById(setMealList);
        //2. 返回成功信息
        return R.success("修改成功");
    }

    /**
     * 根据分类id获取在售套餐列表
     * @param categoryId 分类id
     * @return 返回分类列表
     */
    @GetMapping("/list")
    @Cacheable(value = "setmealCache", key = "'category_' + #categoryId")
    public R<List<SetMeal>> getSetMealListByCategoryId(Long categoryId){
        log.info("根据分类id获取在售套餐列表, categoryId={}",categoryId);
        if (categoryId == null){
            return R.success(new ArrayList<>());
        }
        //1. 调用service查询
        LambdaQueryWrapper<SetMeal> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SetMeal::getCategoryId, categoryId);
        lqw.eq(SetMeal::getStatus,1);
        lqw.orderByAsc(SetMeal::getUpdateTime);
        List<SetMeal> setMealList = setMealService.list(lqw);
        //2. 异常处理 -categoryId ==null
        //3. 返回列表
        return R.success(setMealList);
    }
}
